/*
 * File:    Procedure.java
 * Created: 01-Mar-2009
 * Version: $Id$
 *
 * COPYRIGHT (C) 2009, Bitgate Mobile, LLC.  All Rights Reserved.
 *
 * software@bitgatemobile.com
 */

package com.webplasm.render.tags.u;

import java.util.Arrays;
import java.util.List;

import com.webplasm.context.RenderContext;
import com.webplasm.render.engine.RenderException;
import com.webplasm.render.tags.TagInterface;
import com.webplasm.render.tags.WrappedNode;

/**
 * Allows for a block of code to be stored in a procedure that can be called with specific parameters sent to it.
 * 
 * @author kenji
 * @since Webplasm 1.0
 */
public class Procedure extends WrappedNode implements TagInterface {
	private static final String DESCRIPTION = "Defines a procedure locally or globally.";
	
	public static final String PROCEDURE_SCOPE_LOCAL = "local";
	public static final String PROCEDURE_SCOPE_GLOBAL = "global";

	public String getNamespace() {
		return "u";
	}
	
	public List<String> getAttributes() {
		return Arrays.asList("name", "scope", "variables");
	}
	
	public List<String> getManagedNodes() {
		return null;
	}

	public String getDescription() {
		return DESCRIPTION;
	}

	@Override
	public StringBuffer render(RenderContext rContext) throws RenderException {
		if (elements.get("name") == null) {
			throw new RenderException("u:procedure requires a procedure name.");
		}
		
		String procedureScope = elements.get("scope");
		
		if (procedureScope == null) {
			procedureScope = PROCEDURE_SCOPE_LOCAL;
		}
		
		if (procedureScope.equalsIgnoreCase(PROCEDURE_SCOPE_LOCAL)) {
			List<String> variables = null;
			
			if (elements.get("variables") != null) {
				variables = Arrays.asList(elements.get("variables").split(","));
			}
			
			rContext.getLocalProcedureStore().addProcedure(elements.get("name"), new WrappedNode(super.thisNode), variables);
		} else if (procedureScope.equalsIgnoreCase(PROCEDURE_SCOPE_GLOBAL)) {
		} else {
			throw new RenderException("u:procedure requires a valid procedure scope: global or local.");
		}
		
		return new StringBuffer();
	}
}